import { Course } from '../../types/course'
import { Page, PageReq } from '../../types/page'
import { CourseDao } from '../dao/courseDao'
import {CourseTimeService} from './courseTimeService'

export class CourseService {
  /**
   * 创建课程
   */
  static async create(course: Omit<Course, 'id'>): Promise<number | undefined> {
    //根据course_time查询
    const courseTime = await CourseTimeService.findById(course.course_time)
    //已知course_time查询course_time(hh:mm)表的start_time和end_time(hh:mm)
    if(courseTime){
      //计算courseTime.start_time到  courseTime.start_time相隔几秒            
       const startTime = new Date( '2025-09-05T'+courseTime.start_time+':00')
       const endTime = new Date('2025-09-05T'+courseTime.end_time+':00')
       const total_time = (endTime.getTime() - startTime.getTime()) / 1000
       course.total_time = total_time
    }
    return CourseDao.create(course)
  }

  /**
   * 更新课程信息
   */
  static async update(id: number, course: Partial<Course>): Promise<void> {
    //根据course_time查询
    const courseTime = await CourseTimeService.findById(course.course_time)
    if(courseTime){
      //计算courseTime.start_time到  courseTime.start_time相隔几秒            
       const startTime = new Date( '2025-09-05T'+courseTime.start_time+':00')
       const endTime = new Date('2025-09-05T'+courseTime.end_time+':00')
       const total_time = (endTime.getTime() - startTime.getTime()) / 1000
       course.total_time = total_time
    }
    return CourseDao.update(id, course)
  }

  /**
   * 删除课程
   */
  static async delete(id: number): Promise<void> {
    return CourseDao.delete(id)
  }

  /**
   * 获取课程详情
   */
  static async getById(id: number): Promise<Course | null> {
    return CourseDao.getById(id)
  }

  /**
   * 获取课程列表
   */
  static async list(): Promise<Course[]> {
    return CourseDao.list()
  }

  /**
   * 分页查询课程列表
   */
  static async page(params: PageReq<Course>): Promise<Page<Course>> {
    return CourseDao.page(params)
  }

}